package wechat

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"github.com/pkg/errors"
	"jk-webook/internal/domain"
	"net/http"
	"net/url"
)

var redirectURI = url.PathEscape("sdsds")

type Service interface {
	AuthURL(ctx context.Context) (string, error)
	VerifyCode(ctx context.Context, code, state string) (domain.WeChatInfo, error)
}
type service struct {
	appId     string
	appSecret string
	client    http.Client
}

func NewService(appId, appSecret string) *service {
	return &service{appId: appId, appSecret: appSecret}
}
func (s *service) AuthURL(ctx context.Context) (string, error) {
	const urlPattern = "xdsdsds"
	state := uuid.New()
	return fmt.Sprintf(urlPattern, s.appId, redirectURI, state), nil
}
func (s *service) VerifyCode(ctx context.Context, code, state string) (domain.WeChatInfo, error) {
	const urlPattern = "xdsdsds"
	target := fmt.Sprintf(urlPattern, s.appId, s.appSecret, code, state)
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)

	if err != nil {
		return domain.WeChatInfo{}, err
	}
	do, err := s.client.Do(req)
	if err != nil {
		return domain.WeChatInfo{}, err
	}
	decoder := json.NewDecoder(do.Body)
	var res Result
	err = decoder.Decode(&res)
	if err != nil {
		return domain.WeChatInfo{}, err
	}
	if res.ErrCode != 0 {
		return domain.WeChatInfo{}, errors.New("微信返回错误信息")
	}
	return domain.WeChatInfo{}, nil
}

type Result struct {
	ErrCode int64 `json:"err_code"`
}
